import { useEffect, useState } from 'react'
import { getSpuOptions } from '@/api/goods'
export interface ISpuType {
  id: number
  phone: string
  name: string
  orgId: string
  workId: string
}
const useSearchSpu = (Key: 'spuCode' | 'spuId' = 'spuCode') => {
  let SpuTimeout: ITimeoutType
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const handleSearchSpu = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        spuId: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item[Key],
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  return { SpuOptions, setSpuOptions, handleSearchSpu }
}

export default useSearchSpu
